//
//  CYEnterDrawCashVC.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/13.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYEnterDrawCashVC.h"
#import "CYDrawCashDetailView.h"
#import "CYPassWordView.h"
#import "CYReInputField.h"
@interface CYEnterDrawCashVC ()<UITextFieldDelegate>{
    CGFloat _keyboardHeight;
}
@property (nonatomic, strong) CYDrawCashDetailView *detailView;
@property (nonatomic, strong) CYLabel *drawMondyLBL;//提款金额
@property (nonatomic, strong) UITextField *textfield;
@property (nonatomic, strong) CYView *textBackView; //
@property (nonatomic, strong) CYButton *enterBtn;
@property (nonatomic, strong) CYLabel *signLBL; //人民币标志
@property (nonatomic, strong) CYPassWordView *passwordView; //输入密码界面
@property (nonatomic, strong) CYView *alphaView; //半透明背景
@property (nonatomic, strong) CYView *alpha_reInputView; //重新输入背景
@property (nonatomic, strong) CYReInputField *reInputView;//重新输入
@property (nonatomic, strong) CYUser *userModel;
@end

@implementation CYEnterDrawCashVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.detailView.hidden = self.textBackView.hidden = self.drawMondyLBL.hidden = NO;
    self.signLBL.hidden = self.textfield.hidden = NO;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionForSigleTap)];
    [self.view addGestureRecognizer:tap];
    
    self.alphaView.hidden = YES;
    self.enterBtn.hidden = NO;
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotification object:nil];
    
    
    // Do any additional setup after loading the view.
}
/*懒加载*/
- (CYDrawCashDetailView *)detailView {
    if (!_detailView) {
        _detailView  = [[CYDrawCashDetailView alloc]initWithColor:[UIColor whiteColor]];
        [self.view addSubview:_detailView];
        [self  setupDetailView];
        
        [_detailView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(NAVIBAR_HEIGHT + STATUS_HEIGHT);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, (PT(75 + 12 * 2 + 150 ))));
        }];
    }
    return _detailView;
}

- (CYView *)textBackView{
    if (!_textBackView) {
        _textBackView = [[CYView alloc]initWithColor:[UIColor whiteColor]];
        [self.view addSubview:_textBackView];
        
        [_textBackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_detailView.mas_bottom).with.offset(0);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, AUTO(115)));
        }];
    }
    return _textBackView;
}
- (CYLabel *)drawMondyLBL{
    if (!_drawMondyLBL) {
        _drawMondyLBL = [[CYLabel alloc]initWithText:@"提现金额" size:13 textcolor:ColorHex(0x888888)];
        [_textBackView addSubview:_drawMondyLBL];
        
        WS(_textBackView)
        [_drawMondyLBL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_detailView.mas_bottom).with.offset(10);
            make.left.equalTo(weakSelf).with.offset(20);
            make.size.mas_equalTo(_drawMondyLBL.bounds.size);
        }];
    }
    return _drawMondyLBL;
}

- (UITextField *)textfield{
    if (!_textfield) {
        _textfield = [[UITextField alloc]init];
        [_textfield setValue:ColorHex(0xe2dfdf) forKeyPath:@"_placeholderLabel.textColor"];
        [_textfield setValue:[UIFont boldSystemFontOfSize:AL(PT(40))] forKeyPath:@"_placeholderLabel.font"];
        _textfield.placeholder = [NSString stringWithFormat:@"可提现余额:%.2f元",([CYUser shareUser].keTi> 0)?[CYUser shareUser].keTi:0.0];
        _textfield.delegate = self;
        [_textBackView addSubview:_textfield];
        
        [_textfield mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_textBackView);
            make.left.equalTo(_signLBL.mas_right).with.offset(23);
            make.right.equalTo(_textBackView).with.offset(-20);
            make.height.mas_equalTo(AUTO(50));
        }];
    }
    return _textfield;
}

- (CYButton *)enterBtn{
    if (!_enterBtn) {
        _enterBtn = [[CYButton alloc]initWithTitle:@"确认提现" titleColor:[UIColor lightGrayColor] backgroundColor:ColorHex(0xdcdcdc) cornerRadius:AL(5.0)];
        [_enterBtn addTarget:self action:@selector(actionForEnterDrawCashBtn) forControlEvents:UIControlEventTouchUpInside];
        _enterBtn.userInteractionEnabled = NO;
        [self.view addSubview:_enterBtn];
        
        [_enterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_textBackView.mas_bottom).with.offset(25);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 40, 44));
        }];
    }
    return _enterBtn;
}

- (CYLabel *)signLBL{
    if (!_signLBL) {
        _signLBL = [[CYLabel alloc]initWithText:@"¥" size:30 weight:UIFontWeightBold];
        [_textBackView addSubview:_signLBL];
        
        [_signLBL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_textBackView);
            make.left.equalTo(_drawMondyLBL).with.offset(10);
            make.size.mas_equalTo(_signLBL.bounds.size);
        }];
    }
    return _signLBL;
}

- (CYPassWordView *)passwordView{
    if (!_passwordView) {
        WS(self)
        _passwordView = [[CYPassWordView alloc]initWithColor:ColorHex(0xf5f5f9) block:^(NSString *password) {
            [weakSelf actionForPasswordView:(NSString *)password];
        }];
        [self.view addSubview:_passwordView];
        
        [_passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_bottom).with.offset(0);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, AUTO(335)));
        }];
    }
    return _passwordView;
}

- (CYView *)alphaView{
    if (!_alphaView) {
        _alphaView = [[CYView alloc]initWithColor:ColorHex(0x888888)];
        _alphaView.alpha = 0.5;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionForSigleTap)];
        [_alphaView addGestureRecognizer:tap];
        [self.view addSubview:_alphaView];
        
        [_alphaView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(0.0, 0, 0, 0));
        }];
    }
    return _alphaView;
}

- (CYView *)alpha_reInputView{
    if (!_alpha_reInputView) {
        _alpha_reInputView = [[CYView alloc]initWithColor:ColorHex(0x888888)];
        _alpha_reInputView.alpha = 0.5;
        [self.view addSubview:_alpha_reInputView];
        
        [_alpha_reInputView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(0.0, 0, 0, 0));
        }];
    }
    return _alpha_reInputView;
    
    
}

- (CYReInputField *)reInputView{
    if (!_reInputView) {
        WS(self)
        _reInputView = [[CYReInputField alloc]initWithColor:[UIColor whiteColor] cornerRadius:AL(PT(5.0)) reInputBlock:^(NSString *string) {
            if ([string isEqualToString:@"忘记密码"])
                [weakSelf forgetPassWord];
            else if ([string isEqualToString:@"重新输入"])
                [weakSelf reInputPassWord];
        }];
        [self.view addSubview:_reInputView];
        [_reInputView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(242, 100));
        }];
    }
    return _reInputView;
}

- (void)setUserModel:(CYUser *)userModel{
    if (_userModel != userModel) {
        _userModel = userModel;
        [CYUser shareUser].account = _userModel.account;
        [CYUser shareUser].bankApiImgUrl = _userModel.bankApiImgUrl;
        [CYUser shareUser].bankName = _userModel.bankName;
        [CYUser shareUser].keTi = _userModel.keTi;
        [CYUser shareUser].coin = _userModel.coin;
    }
}
//监听键盘的高度,判断是否遮挡登陆按钮
- (void)keyboardWillShow:(NSNotification *)notification{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    _keyboardHeight = keyboardRect.size.height;
    CGFloat map = SCREEN_HEIGHT - CGRectGetMaxY(_enterBtn.frame) - _keyboardHeight - 10;
    if (map < 0 && _textfield.editing)
        [UIView animateWithDuration:0.3 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, map);
            
        }];
}

- (void)setupDetailView{
    
    _detailView.balance = [CYUser shareUser].coin;//余额
    _detailView.availableBalance = [CYUser shareUser].keTi;;//可用余额
    _detailView.bank = [CYUser shareUser].bankName;//银行
    _detailView.account = [NSString spaceBetweenFourCharacters:[CYUser shareUser].account];//账号
    [CYHttps loadingWithFile:[CYUser shareUser].bankApiImgUrl complete:^(id data) {
        _detailView.bank_image = data;
    }];
    
}
//密码有值，则执行验证，没有值，则表示是执行取消按钮事件
- (void)actionForPasswordView:(NSString *)password{
    
    if (password.length == 0 || password == nil)
        _alphaView.hidden = YES; //点击取消按钮，隐藏背景半透明视图
    else if (password.length > 0)
        [self judgePassword:password];//如果有值，则判断密码
}

//确认提现
- (void)actionForEnterDrawCashBtn{
    [self.view endEditing:YES];
    [_textfield resignFirstResponder];
    [self.passwordView show];//弹出密码输入框
}

//单击触摸
- (void)actionForSigleTap{
    _alphaView.hidden = YES;
    [_passwordView hidden];
}

//检测密码
- (void)judgePassword:(NSString *)password{
    self.alpha_reInputView.hidden = self.reInputView.hidden = YES;
    if (password.length >0) {
        DeLog(@"验证成功");
        NSDictionary *draw_para = @{@"money":_textfield.text,@"password":password,@"username":[CYUser shareUser].username, @"token":[CYUser shareUser].token};
        self.task = [CYHttps POST:API_draw parameters:draw_para showHUD:YES progress:nil success:^(id data) {
            if (data){
                [self pushNextController];//跳到提现成功页面
                [self performSelector:@selector(actionForSigleTap)];//提现成功后， 执行隐藏密码输入界面
                [self https];//提现成功后，刷新本界面可提现余额等提示
            }
        } failure:^(id string) {
            [self performSelector:@selector(actionForSigleTap)];
        }];
    }
    
}

//提现成功后，再次请求绑定银行卡接口，获取最新的可提现余额
- (void)https{
    
    //银行卡是否绑定请求
    NSDictionary *para = @{@"username":[CYUser shareUser].username, @"token":[CYUser shareUser].token};
    self.spareTask = [CYHttps POST:API_isBindCart parameters:para showHUD:NO progress:nil success:^(id data) {
        if (data)
            self.userModel = [CYUser mj_objectWithKeyValues:data];
    } failure:nil];
    
}
//忘记密码
- (void)forgetPassWord{
    
}

//重新输入
- (void)reInputPassWord{
    _alpha_reInputView.hidden = _reInputView.hidden = YES;
    [_passwordView reInput];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [_passwordView hidden];
    return YES;
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    self.passwordView.money = textField.text;
    [UIView animateWithDuration:0.3 animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (![NSString judgeInputIsNumber:string] && ![string isEqualToString:@"."] )//如果输入的不是数字，或者小数点，或者已经包含小数点，不生效
        return NO;
    else if ([string isEqualToString:@"."] && [(NSString *)textField.text containsString:@"."])//如果输入数字已经是小数，不能再输入小数点
        return NO;
    
    if (string.length > 0 || textField.text.length > 1) {
        _enterBtn.backgroundColor = THEME_COLOR;
        _enterBtn.userInteractionEnabled = YES;
        [_enterBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    else{
        _enterBtn.userInteractionEnabled = NO;
        _enterBtn.backgroundColor = ColorHex(0xdcdcdc);
        [_enterBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    NSRange newrange = [textField.text rangeOfString:@"."];
    DeLog(@"length:%lu   location:%lu",newrange.length,newrange.location);
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}
//clear后，按钮显灰色
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    _enterBtn.backgroundColor = ColorHex(0xdcdcdc);
    return YES;
}

- (void)pushNextController{
    Class vc = NSClassFromString(@"CYDrawCashSuccessVC");
    [self.navigationController pushViewController:[vc new] animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.textfield.text = nil;
    [self https];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_passwordView removeFromSuperview];
    _passwordView = nil;
    
    
}

- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:color];
    self.view.backgroundColor = ColorHex(0xf5f5f9);
    self.navigationItem.title = @"提现";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
